package com.bruce.tool.rpc.http.handler.response;

import com.bruce.tool.common.exception.BaseRuntimeException;
import com.bruce.tool.common.exception.ErrorCode;
import com.bruce.tool.common.util.string.JsonUtils;
import com.bruce.tool.common.util.string.StringUtils;
import com.bruce.tool.rpc.http.core.Https;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.ResponseBody;

import java.io.IOException;
import java.util.Map;

/**
 * 功能 :
 * 文件下载,结果集处理类
 * @author : Bruce(刘正航) 下午11:45 2018/7/25
 */
@Slf4j
public class ByteResponseHandler extends ResponseAdapter<byte[]> {

    @Override
    public byte[] handle(Response response) throws IOException {
        ResponseBody body = response.body();

        if( null == body ){return new byte[0]; }

        String contentType = response.header("Content-Type");

        if (StringUtils.isEmpty(contentType)) { return new byte[]{0}; }

        // 下载逻辑里边,只要出现json格式的数据,一定是异常信息
        if (contentType.contains(Https.JSON.subtype())) {
            byte[] result = body.bytes();
            Map object = JsonUtils.strToObj(new String(result), Map.class);
            if( result.length > 0 ){
                Object message = object.get("message");
                throw new BaseRuntimeException(ErrorCode.SYSTEM_ERROR.getCode(),String.valueOf(message));
            }
            return result;
        }

        return body.bytes();
    }

}
